import React, { useState } from 'react';
import { StyleSheet, View, TouchableOpacity, ScrollView, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { TextInput, Button } from 'react-native-paper';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';

import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import { useAuth } from '@/contexts/AuthContext';

export default function EditProfileScreen() {
  const colorScheme = useColorScheme();
  const tintColor = Colors[colorScheme ?? 'light'].tint;
  const router = useRouter();
  const { userInfo, updateProfile } = useAuth();
  
  // 表单状态
  const [name, setName] = useState(userInfo?.name || '');
  const [age, setAge] = useState(userInfo?.age || '');
  const [location, setLocation] = useState(userInfo?.location || '');
  const [bio, setBio] = useState(userInfo?.bio || '');
  const [isLoading, setIsLoading] = useState(false);
  
  // 兴趣爱好状态（简单实现，实际应用可能需要更复杂的管理）
  const [interests, setInterests] = useState<string[]>(userInfo?.interests || []);
  const [newInterest, setNewInterest] = useState('');
  
  // 添加兴趣爱好
  const addInterest = () => {
    if (newInterest.trim() && !interests.includes(newInterest.trim())) {
      setInterests([...interests, newInterest.trim()]);
      setNewInterest('');
    }
  };
  
  // 移除兴趣爱好
  const removeInterest = (interest: string) => {
    setInterests(interests.filter(item => item !== interest));
  };
  
  // 验证年龄
  const validateAge = (age: string) => {
    const ageNum = parseInt(age, 10);
    return !isNaN(ageNum) && ageNum >= 18 && ageNum <= 120;
  };
  
  // 保存个人资料
  const handleSave = async () => {
    // 表单验证
    if (!name) {
      Alert.alert('错误', '姓名不能为空');
      return;
    }
    
    if (age && !validateAge(age)) {
      Alert.alert('错误', '请输入有效的年龄（18-120岁）');
      return;
    }
    
    setIsLoading(true);
    try {
      const success = await updateProfile({
        name,
        age,
        location,
        bio,
        interests,
      });
      
      if (success) {
        Alert.alert('成功', '个人资料已更新', [
          { text: '确定', onPress: () => router.back() }
        ]);
      } else {
        Alert.alert('错误', '更新个人资料失败，请重试');
      }
    } catch (error) {
      Alert.alert('错误', '发生未知错误，请重试');
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };
  
  return (
    <ThemedView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
          <MaterialCommunityIcons name="arrow-left" size={28} color={tintColor} />
        </TouchableOpacity>
        <ThemedText style={styles.headerTitle}>编辑个人资料</ThemedText>
        <View style={styles.placeholder} />
      </View>
      
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoidingView}
      >
        <ScrollView style={styles.scrollView}>
          <View style={styles.formContainer}>
            <TextInput
              label="姓名"
              value={name}
              onChangeText={setName}
              mode="outlined"
              style={styles.input}
              left={<TextInput.Icon icon="account" color={tintColor} />}
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />
            
            <TextInput
              label="年龄"
              value={age}
              onChangeText={setAge}
              mode="outlined"
              style={styles.input}
              keyboardType="number-pad"
              left={<TextInput.Icon icon="calendar" color={tintColor} />}
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />
            
            <TextInput
              label="所在地"
              value={location}
              onChangeText={setLocation}
              mode="outlined"
              style={styles.input}
              left={<TextInput.Icon icon="map-marker" color={tintColor} />}
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />
            
            <TextInput
              label="个人简介"
              value={bio}
              onChangeText={setBio}
              mode="outlined"
              style={styles.textArea}
              multiline
              numberOfLines={4}
              left={<TextInput.Icon icon="text" color={tintColor} />}
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />
            
            <View style={styles.interestsSection}>
              <ThemedText style={styles.sectionTitle}>兴趣爱好</ThemedText>
              
              <View style={styles.interestInputContainer}>
                <TextInput
                  label="添加兴趣爱好"
                  value={newInterest}
                  onChangeText={setNewInterest}
                  mode="outlined"
                  style={styles.interestInput}
                  outlineColor="#CCCCCC"
                  activeOutlineColor={tintColor}
                  theme={{ roundness: 10 }}
                  right={
                    <TextInput.Icon 
                      icon="plus" 
                      color={tintColor} 
                      onPress={addInterest} 
                    />
                  }
                />
              </View>
              
              <View style={styles.interestTags}>
                {interests.map((interest, index) => (
                  <View key={index} style={styles.interestTag}>
                    <ThemedText style={styles.interestTagText}>{interest}</ThemedText>
                    <TouchableOpacity onPress={() => removeInterest(interest)}>
                      <MaterialCommunityIcons name="close" size={16} color="#666" />
                    </TouchableOpacity>
                  </View>
                ))}
              </View>
            </View>
            
            <Button
              mode="contained"
              onPress={handleSave}
              style={styles.saveButton}
              loading={isLoading}
              disabled={isLoading}
              buttonColor={tintColor}
            >
              保存修改
            </Button>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingTop: 60,
    paddingBottom: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#E1E1E1',
  },
  backButton: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
  headerTitle: {
    fontSize: 22,
    fontWeight: 'bold',
  },
  placeholder: {
    width: 40,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
  },
  formContainer: {
    padding: 20,
  },
  input: {
    marginBottom: 16,
    backgroundColor: 'transparent',
  },
  textArea: {
    marginBottom: 16,
    backgroundColor: 'transparent',
    height: 120,
  },
  interestsSection: {
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  interestInputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  interestInput: {
    flex: 1,
    backgroundColor: 'transparent',
  },
  interestTags: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 10,
  },
  interestTag: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#F0F0F0',
    borderRadius: 20,
    paddingHorizontal: 12,
    paddingVertical: 6,
    marginRight: 8,
    marginBottom: 8,
  },
  interestTagText: {
    marginRight: 5,
    fontSize: 14,
  },
  saveButton: {
    marginTop: 20,
    paddingVertical: 8,
    borderRadius: 10,
  },
});